#!/bin/sh

echo "Starting NFS"

echo "$DATA_PATH *(fsid=root,rw,insecure,async,no_subtree_check,no_root_squash,anonuid=$BTSYNC_UID,anongid=$BTSYNC_GID)" > /etc/exports

if [ -e /proc/modules ] ; then
	# Make sure nfs support is loaded in the kernel #64709
	if ! grep -qs nfsd /proc/filesystems ; then
		modprobe -q nfsd
	fi
	# Restart idmapd if needed #220747
	if grep -qs nfsd /proc/modules ; then
		killall -q -HUP rpc.idmapd
	fi
fi

# This is the new "kernel 2.6 way" to handle the exports file
if grep -qs nfsd /proc/filesystems ; then
	if ! grep -qs "nfsd /proc/fs/nfsd" /proc/mounts ; then
		echo "Mounting nfsd filesystem in /proc"
		mount -t nfsd -o nodev,noexec,nosuid nfsd /proc/fs/nfsd
	fi
fi

for d in rpc_pipefs v4recovery v4root ; do
	d="/var/lib/nfs/${d}"
	[ ! -d "${d}" ] && mkdir -p "${d}"
done
chown -R ${BTSYNC_UID}:${BTSYNC_GID} /var/lib/nfs

rpcbind;
rpc.mountd -F & sleep 1;

exportfs -ar;

rpc.nfsd \
	-N 2 -N 3 -V 4 \
	-d --port $NFS_PORT $NFS_NUM_SERVERS

rpc.statd -F -d & sleep 1;

echo "NFS started"

# Ugly hack
while true; do
	read;
done;
